package com.jin.webvideo.config.filter;

import com.jin.webvideo.base.LoginHandler;
import com.jin.webvideo.entity.SessionStore;
import com.jin.webvideo.base.util.SystemInfo;
import com.jin.webvideo.util.base.StringUtil;
import com.jin.webvideo.util.sys.EncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class TraceFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(TraceFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest httpServletRequest) {
            SessionStore session = LoginHandler.getSessionStore(httpServletRequest);
            if (session == null) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            if (StringUtil.isEmpty(session.getTraceId())) {
                String remoteAddr = httpServletRequest.getRemoteAddr();
                session.setTraceId( EncryptUtil.md5Hex(remoteAddr + SystemInfo.now()) );
                MDC.put("traceId", session.getTraceId());
                LOGGER.trace(String.format("create new traceId for remoteAddr=%s", remoteAddr));
            }
            MDC.put("traceId", session.getTraceId());
            LOGGER.trace(httpServletRequest.getRequestURI());
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
